package com.cxd.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.cxd.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
@DefaultProperties(defaultFallback = "global_payment_exception")
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String sayHelloOk(Integer id) {
        return Thread.currentThread().getName() + "\t" + "id: " + id + "哈哈哈๑乛◡乛๑";
    }

    @Override
    // @HystrixCommand(fallbackMethod = "paymentInfo_timeout",commandProperties = {
    //         @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    // })
    @HystrixCommand
    public String sayHelloTimeOut(Integer id) {
        try {
            Thread.sleep(13000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "\t" + "id: " + id + " 超时了(Ｔ▽Ｔ)";
    }


    public String paymentInfo_timeout(Integer id) {
        return "8001系统繁忙，请稍后重试";
    }

    public String global_payment_exception() {
        return "GLOBAL 异常处理，系统繁忙，请稍后重试";
    }

    //------------服务熔断-------------------
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期（时间范围）
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少后熔断
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("***********id 不能为负数");
        }
        String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + uuid;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id")Integer id) {
        return "id 不能为负数，请稍后重试 id: " + id;
    }
}
